<template>
  <u-upload class="u-upload" :ref="refName" :fileList="filelist" v-bind="$attrs" :width="width" :height="height" @afterRead="afterRead" @delete="deletePic" :deletable="deletable" :maxCount="maxCount">
    <slot>
      <image src="https://zxtest001.oss-cn-beijing.aliyuncs.com/l-owner-uni3/img_upload.png" :mode="imgMode" :style="{ width: width + 'rpx', height: height + 'rpx' }"></image>
    </slot>
  </u-upload>
</template>

<script setup lang="ts">
/**
 * upload 上传
 * @description 该组件用于上传图片场景
 * @tutorial https://uviewui.com/components/upload.html
 * @property {String}			accept				接受的文件类型, 可选值为all media image file video （默认 'image' ）
 * @property {String | Array}	capture				图片或视频拾取模式，当accept为image类型时设置capture可选额外camera可以直接调起摄像头（默认 ['album', 'camera'] ）
 * @property {Boolean}			compressed			当accept为video时生效，是否压缩视频，默认为true（默认 true ）
 * @property {String}			camera				当accept为video时生效，可选值为back或front（默认 'back' ）
 * @property {Number}			maxDuration			当accept为video时生效，拍摄视频最长拍摄时间，单位秒（默认 60 ）
 * @property {String}			uploadIcon			上传区域的图标，只能内置图标（默认 'camera-fill' ）
 * @property {String}			uploadIconColor		上传区域的图标的字体颜色，只能内置图标（默认 #D3D4D6 ）
 * @property {Boolean}			useBeforeRead		是否开启文件读取前事件（默认 false ）
 * @property {Boolean}			previewFullImage	是否显示组件自带的图片预览功能（默认 true ）
 * @property {String | Number}	maxCount			最大上传数量（默认 52 ）
 * @property {Boolean}			disabled			是否启用（默认 false ）
 * @property {String}			imageMode			预览上传的图片时的裁剪模式，和image组件mode属性一致（默认 'aspectFill' ）
 * @property {String}			name				标识符，可以在回调函数的第二项参数中获取
 * @property {Array}			sizeType			所选的图片的尺寸, 可选值为original compressed（默认 ['original', 'compressed'] ）
 * @property {Boolean}			multiple			是否开启图片多选，部分安卓机型不支持 （默认 false ）
 * @property {Boolean}			deletable			是否展示删除按钮（默认 true ）
 * @property {String | Number}	maxSize				文件大小限制，单位为byte （默认 Number.MAX_VALUE ）
 * @property {Array}			fileList			显示已上传的文件列表
 * @property {String}			uploadText			上传区域的提示文字
 * @property {String | Number}	width				内部预览图片区域和选择图片按钮的区域宽度（默认 80 ）
 * @property {String | Number}	height				内部预览图片区域和选择图片按钮的区域高度（默认 80 ）
 * @property {Object}			customStyle			组件的样式，对象形式
 * @event {Function} afterRead		读取后的处理函数
 * @event {Function} beforeRead		读取前的处理函数
 * @event {Function} oversize		文件超出大小限制
 * @event {Function} clickPreview	点击预览图片
 * @event {Function} delete 		删除图片
 */
import { ref, watch, toRaw } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import config from '@/config/api';
import { getBasicOss } from '@/model';
import OSS from 'ali-oss';
import dayjs from 'dayjs';
import ImgZipper from 'imgzipper';

const props = defineProps({
  files: {
    type: Object,
  },
  refName: {
    type: String,
    default: 'uupload',
  },
  width: {
    type: Number,
    default: 224,
  },
  height: {
    type: Number,
    default: 224,
  },
  maxCount: {
    type: Number,
    default: 52,
  },
  deletable: {
    type: Boolean,
    default: true,
  },
  imgMode: {
    type: String,
    default: 'aspectFill'
  }
});
const emits = defineEmits(['on-change']);
const filelist: any = ref([]);
const uupload: any = ref();
const bucketStr = ref('zxtest001');
let ossInfo: any = '';
watch(
  () => props.files,
  (newVal: any) => {
    filelist.value = newVal;
  },{immediate: true}
);

onLoad(async () => {
  // #ifdef H5
  if (import.meta.env.MODE == 'production') {
    bucketStr.value = 'asal';
  }
  // #endif
  //#ifdef MP-WEIXIN || MP-ALIPAY
  bucketStr.value = config.bucket;
  // #endif
  const data = await getBasicOss({ bucket: bucketStr.value });
  ossInfo = data;
});
const zipImg = (file: any) => {
  try {
    const imageType = file.type.includes('image');

    if (imageType) {
      return new Promise((res, rej) => {
        ImgZipper(
          file,
          (a: any, b: any) => {
            const zipfile = new File([a], file.name, { type: file.type, lastModified: Date.now() });
            res(zipfile);
          },
          {
            scale: 0.78, // 生成图像缩放大小
            quality: 0.62, // 生成图像的质量
            disableBlob: null, // canvas.toBlob方法失败后调用函数
            type: 'image/jpeg', // 生成图像格式
            exif: true, // 是否使用调整相机旋转
          }
        );
      });
    } else {
      return Promise.resolve(file);
    }
  } catch (err) {
    throw err;
  } finally {
  }
};

const uploadFilePromise = (file: any) => {
  return new Promise(async (resolve, reject) => {
    fetch(file.url)
      .then((response) => response.blob())
      .then(async (blob) => {
        // FIXME: zipImg 小程序报错
        const newFile: any = await zipImg(blob)?.catch();
        console.log('newFile: ', newFile);
        const client = new OSS({
          region: ossInfo.region,
          accessKeyId: ossInfo.AccessKeyId,
          accessKeySecret: ossInfo.AccessKeySecret,
          stsToken: ossInfo.SecurityToken,
          bucket: ossInfo.bucket,
        });

        const result = await client.put(`/${config.uploadOssFolder}/${dayjs().valueOf()}${file.name}`, newFile);
        console.log('client =====', result);
        resolve(result);
      })
      .catch((error) => {
        // 处理错误
        console.error(error);
      });
  });
};

const deletePic = (event: any) => {
  console.log(6666,event.index);
  
  filelist.value.splice(event.index, 1);
  console.log(7777,filelist.value);
  emits('on-change', toRaw(filelist.value));
};

const afterRead = async (event: any) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  console.log('after read ======', event.file);
  let lists: any = [].concat(event.file);
  let fileListLen = filelist.value.length;
  lists.map((item: any) => {
    filelist.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result: any = await uploadFilePromise(lists[i]);
    console.log('======', result);
    let item = filelist.value[fileListLen];
    filelist.value.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: result.url,
    });
    fileListLen++;
  }
  emits('on-change', toRaw(filelist.value));
};
</script>

<style>
::v-deep .u-upload__deletable{
  background-image: url('https://asa-hr.oss-cn-beijing.aliyuncs.com/HR-h5/delete.png');
  background-size: 100% auto;
  background-repeat: no-repeat;
  background-color:transparent !important;
  width: 80rpx !important;
  height: 80rpx !important;
  
}
::v-deep .u-upload__deletable__icon{
  display: none !important;
}

</style>
